package com.qiaofang.applet.service.other.service.impl;

import com.qiaofang.applet.common.client.weixin.WxService;
import com.qiaofang.applet.common.client.weixin.model.WxProperties;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.constants.BusinessConstants;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.QiNiuService;
import com.qiaofang.applet.service.other.service.WxaQrCodeService;
import com.qiaofang.applet.service.other.service.dto.WxaQrCodeDto;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.domain.Property;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

/**
 * 小程序二维码
 * @author junze.liu
 */
@Slf4j
@Service
public class WxaQrCodeServiceImpl implements WxaQrCodeService {

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private WxService wxService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private QiNiuService qiNiuService;

    /**
     * 二手房和租房path
     */
    private final String SALE_RENT_URL = "/pages/ershoufang/details/main?id=%s&type=%s";

    /**
     * 新房path
     */
    private final String FE_URL = "/pages/newhouse/details/main?id=";

    /**
     * 经纪人Path
     */
    private final String EM_URL = "/pages/employee/main?employeeUniqueUuid=";

    /**
     * 咨询详情Path
     */
    private final String ASSETS_URL = "pages/informationdetail/main?id=%s&cityCode=%s";


    @Override
    public String createQrCode(WxaQrCodeDto dto) {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        if(StringUtils.isBlank(corporationCode)) {
            log.error("创建小程序二维码，未获取到集团code");
            throw new BusinessException("创建小程序二维码，未获取到集团code");
        }
        //获取小程序appid
        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);
        WxProperties config = new WxProperties();
        config.setAppId(corporation.getAuthAppId());
        config.setAppSecret(corporation.getAuthAppSecret());
        //小程序端获取二维码
        if(StringUtils.isNotBlank(dto.getPath())) {
            return getMiniQrCode(dto.getPath(), config);
        }
        //pc端获取二维码
        if(BusinessConstants.SALE_PROPERTY.getValue().equals(dto.getBusinessType()) || BusinessConstants.RENT_PROPERTY.getValue().equals(dto.getBusinessType())) {
            //二手房、租房
            return getSaleOrRentQrCode(dto.getBusinessUniqueUuid(), dto.getBusinessType(), config);
        } else if(BusinessConstants.FIRSTHAND_ESTATE.getValue().equals(dto.getBusinessType())) {
            //新房
            return getFirsthandEstateQrCode(dto.getBusinessUniqueUuid(), config);
        }else if (BusinessConstants.EMPLOYEE.getValue().equals(dto.getBusinessType())){
            //经纪人
            return getEmployeeQrCode(dto.getBusinessUniqueUuid(), config);
        }
        return null;
    }

    /**
     * 小程序端获取小程序二维码
     * @param path
     * @param config
     * @return
     */
    private String getMiniQrCode(String path, WxProperties config) {
        byte[] result = wxService.getCreateQRCode(path, config);
        String strBase64 = new BASE64Encoder().encode(result);
        return strBase64.replaceAll("\r\n","");
    }

    /**
     * pc端二手房和租房获取小程序二维码
     * @param businessUniqueUuid
     * @param config
     * @return
     */
    private String getSaleOrRentQrCode(String businessUniqueUuid, String businessType, WxProperties config) {
        //查询房源信息
        //Property property = propertyService.findByPropertyUniqueUuid(businessUniqueUuid);
        String type = null;
        if(BusinessConstants.SALE_PROPERTY.getValue().equals(businessType)) {
            type = "2";
        } else if(BusinessConstants.RENT_PROPERTY.getValue().equals(businessType)) {
            type = "3";
        }
        String url = String.format(SALE_RENT_URL, businessUniqueUuid, type);
        //生成小程序二维码
        byte[] result = wxService.getCreateQRCode(url, config);
        //上传到七牛云，并返回链接
        return qiNiuService.getUploadByByte(result);
    }

    /**
     * pc端新房获取小程序二维码
     * @param businessUniqueUuid
     * @param config
     * @return
     */
    private String getFirsthandEstateQrCode(String businessUniqueUuid, WxProperties config) {
        //查询房源信息
        //FirsthandEstate firsthandEstate = firsthandEstateService.findByEstateUniqueUuid(businessUniqueUuid);
        //生成小程序二维码
        byte[] result = wxService.getCreateQRCode(FE_URL + businessUniqueUuid, config);
        //上传到七牛云，并返回链接
        return qiNiuService.getUploadByByte(result);
    }

    /**
     * pc端经纪人获取小程序二维码
     * @param businessUniqueUuid
     * @param config
     * @return
     */
    private String getEmployeeQrCode(String businessUniqueUuid, WxProperties config) {
        //查询房源信息
        //Employee employee = employeeService.findByEmployeeUniqueUuid(businessUniqueUuid);
        //生成小程序二维码
        byte[] result = wxService.getCreateQRCode(EM_URL + businessUniqueUuid, config);
        //上传到七牛云，并返回链接
        return qiNiuService.getUploadByByte(result);
    }

    @Override
    public String createQrCodeToShare(String id) {

        String corporationCode = QfContextHolder.getContext().getCorporationCode();

        if(StringUtils.isBlank(corporationCode)) {
            log.error("创建小程序二维码，未获取到集团code");
            throw new BusinessException("创建小程序二维码，未获取到集团code");
        }
        //获取小程序appid
        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);
        WxProperties config = new WxProperties();
        config.setAppId(corporation.getAuthAppId());
        config.setAppSecret(corporation.getAuthAppSecret());
        return getMiniQrCodeToShare(config, id);
    }

    private String getMiniQrCodeToShare(WxProperties config, String id) {
        String cityCode = QfContextHolder.getContext().getCityCode();
        String url = String.format(ASSETS_URL, id, cityCode);
        byte[] result = wxService.getCreateQRCode(url, config);
        return qiNiuService.getUploadByByte(result);
    }
}
